package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("ExpireService")
@Transactional

public class ExpireServiceImpl extends CmiEmaService implements ExpireService {
	public ExpireServiceImpl() {
	}

	@Transactional
	public Expire saveExpire(Expire expire) {
		Set<Food> existingFoodsForExpire = new HashSet<Food>();

		Set<Food> selectedFoodsForExpire = expire.getFoodsForExpire();

		if (expire.getId() == null) {
			Unit unit = unitDAO.findUnitById(expire.getUnit().getId());

			Expire existingExpire = expireDAO.findExpireByPhysicalPrimaryKey(expire.getQuantity(), unit.getId());

			expire.setUnit(unit);

			if (isEquals(expire, existingExpire)) {
				return existingExpire;
			}

			expire = expireDAO.store(expire);
			expireDAO.flush();

			for (Food relatedFood : selectedFoodsForExpire) {
				relatedFood.setExpire(expire);
				foodDAO.store(relatedFood);
			}
		} else {
			Expire existingExpire = expireDAO.findExpireByPrimaryKey(expire.getId());

			existingFoodsForExpire = existingExpire.getFoodsForExpire();

			Set<Food> prepareDeleteFoodsForExpire = new HashSet<Food>();
			Set<Food> prepareAddFoodsForExpire = new HashSet<Food>();

			prepareDeleteFoodsForExpire.addAll(selectedFoodsForExpire);
			prepareDeleteFoodsForExpire.addAll(existingFoodsForExpire);

			prepareAddFoodsForExpire.addAll(selectedFoodsForExpire);
			prepareAddFoodsForExpire.addAll(existingFoodsForExpire);

			prepareDeleteFoodsForExpire.removeAll(selectedFoodsForExpire);
			prepareAddFoodsForExpire.removeAll(existingFoodsForExpire);

			for (Food relatedFood : prepareAddFoodsForExpire) {
				relatedFood.setExpire(expire);
				foodDAO.store(relatedFood);
			}

			for (Food relatedFood : prepareDeleteFoodsForExpire) {
				relatedFood.setExpire(null);
				foodDAO.store(relatedFood);
			}
			expire = expireDAO.store(expire);
			expireDAO.flush();
		}

		foodDAO.flush();
		return expire;
	}

	public void deleteExpire(Expire expire) {
		expireDAO.remove(expire);
		expireDAO.flush();
	}

	@Transactional
	public void deleteExpires(Set<Integer> deleteExpiresId) {
		Query query = expireDAO.createNamedQuery("deleteExpiresById", -1, -1);
		query.setParameter(1, deleteExpiresId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Expire> loadExpires() {
		return expireDAO.findAllExpires();

	}

	@Transactional
	public Set<Expire> loadReferenceExpires(Set<Expire> expires) {
		Iterator<Expire> expiresIterator = expires.iterator();
		Set<Expire> referencedExpires = new HashSet<>();
		while (expiresIterator.hasNext()) {
			Expire currentExpire = expiresIterator.next();

			if (!currentExpire.getFoodsForExpire().isEmpty()) {
				referencedExpires.add(currentExpire);
				continue;
			}
		}
		return referencedExpires;
	}

	public Set<Expire> loadExpiresByIdSet(Set<Integer> expireIdSet) {

		Iterator<Integer> expireIdIterator = expireIdSet.iterator();
		Set<Expire> expireSet = new HashSet<>();
		while (expireIdIterator.hasNext()) {
			Integer id = expireIdIterator.next();
			Expire currentExpire = expireDAO.findExpireById(id);
			expireSet.add(currentExpire);
		}
		return expireSet;
	}

	@Transactional
	public List<Expire> findAllExpires(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Expire>(expireDAO.findAllExpires(startResult, maxRows));
	}

	@Transactional
	public Expire findExpireByPrimaryKey(Integer id) {
		return expireDAO.findExpireByPrimaryKey(id);
	}

	@Transactional
	public Integer countExpires() {
		return ((Long) expireDAO.createQuerySingleResult("select count(o) from Expire o").getSingleResult()).intValue();
	}

	@Transactional
	public Integer countExpires(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Expire.class);
		return ((Long) expireDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countExpiresByName(String queryName) {
		Query query = expireDAO.createNamedQuery("countExpiresByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countExpiresByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Expire.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadExpireObjectReferencedSet(Expire expire) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (expire.getUnit() != null) {

			Set<Integer> unitIds = new HashSet<Integer>();
			unitIds.add(expire.getUnit().getId());
			objectReferencedSetMap.put("unitIds", unitIds);
		}

		Set<Integer> foodsIds = new HashSet<Integer>();
		for (Food obj : expire.getFoodsForExpire()) {

			foodsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("foodsIds", foodsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadExpireClassReferencedSet(Expire expire) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("units", unitDAO.findAllUnits());
		classReferencedSetMap.put("foods", foodDAO.findAllFoods());

		return classReferencedSetMap;
	}

	public boolean isEquals(Expire expire, Object obj) {
		if (obj == expire)
			return true;
		if (!(obj instanceof Expire))
			return false;
		Expire comparedExpire = (Expire) obj;
		if (!CheckPropertyEqual(expire.getQuantity(), comparedExpire.getQuantity())) {
			return false;
		}
		if (!CheckPropertyEqual(expire.getUnit().getId(), comparedExpire.getUnit().getId())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

